﻿using OrderApi.Data;

using OrderApi.Repositories;
using System.Text;
using OrderApi.Models;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.Linq.Expressions;
using OrderApi.DTOs;
using OrderApi.Helpers;
using Microsoft.EntityFrameworkCore;

namespace OrderApi.Services
{
    public class OrderService : IOrderService
    {
        private readonly IRepository<Order> _orderRepository;

        public OrderService(IRepository<Order> orderRepository)
        {
            _orderRepository = orderRepository;
        }

        public async Task<Order> GetOrderByIdAsync(int id)
        {
            return await _orderRepository.GetByIdAsync(id);
        }

        public async Task<PagedResult<Order>> GetPagedOrdersAsync(int pageNumber, int pageSize)
        {
            return await _orderRepository.GetPagedAsync(pageNumber, pageSize);
        }
        public async Task<PagedResult<Order>> GetDeletedOrdersAsync(int pageNumber = 1, int pageSize = 10)
        {
            // 禁用查询过滤器获取已删除的订单
            return await _orderRepository.GetPagedAsync(
                pageNumber,
                pageSize,
                o => o.IsDeleted,
                true); // 忽略全局查询过滤器
        }
        public async Task<Order> CreateOrderAsync(Order order)
        {
            order.OrderNumber = GenerateOrderNumber();
            await _orderRepository.AddAsync(order);
            await _orderRepository.SaveChangesAsync();
            return order;
        }

        public async Task UpdateOrderAsync(Order order)
        {
            _orderRepository.Update(order);
            await _orderRepository.SaveChangesAsync();
        }

        public async Task DeleteOrderAsync(int id)
        {
            var order = await _orderRepository.GetByIdAsync(id);
            if (order != null)
            {
                _orderRepository.Remove(order);
                await _orderRepository.SaveChangesAsync();
            }
        }

        public async Task<byte[]> ExportOrdersToExcelAsync()
        {
            var orders = await _orderRepository.GetAllAsync();

            // 使用 NPOI 创建 Excel 工作簿
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet("订单列表");

            // 创建标题行样式
            var headerFont = workbook.CreateFont();
            headerFont.IsBold = true;
            headerFont.FontHeightInPoints = 12;

            var headerStyle = workbook.CreateCellStyle();
            headerStyle.SetFont(headerFont);
            headerStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
            headerStyle.FillPattern = FillPattern.SolidForeground;
            headerStyle.Alignment = HorizontalAlignment.Center;
            headerStyle.VerticalAlignment = VerticalAlignment.Center;

            // 创建单元格样式
            var cellStyle = workbook.CreateCellStyle();
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.BorderTop = BorderStyle.Thin;

            var dateStyle = workbook.CreateCellStyle();
            dateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy-mm-dd HH:mm");
            dateStyle.CloneStyleFrom(cellStyle);

            var moneyStyle = workbook.CreateCellStyle();
            moneyStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0.00");
            moneyStyle.CloneStyleFrom(cellStyle);

            // 设置标题行
            var headerRow = sheet.CreateRow(0);
            string[] headers = { "ID", "订单编号", "订单日期", "客户名称", "总金额", "订单状态" };

            for (int i = 0; i < headers.Length; i++)
            {
                var cell = headerRow.CreateCell(i);
                cell.SetCellValue(headers[i]);
                cell.CellStyle = headerStyle;
            }

            // 填充数据
            int rowNum = 1;
            foreach (var order in orders)
            {
                var row = sheet.CreateRow(rowNum++);

                row.CreateCell(0).SetCellValue(order.Id);
                row.CreateCell(1).SetCellValue(order.OrderNumber);

                var dateCell = row.CreateCell(2);
                dateCell.SetCellValue(order.OrderDate);
                dateCell.CellStyle = dateStyle;

                row.CreateCell(3).SetCellValue(order.CustomerName);

                var moneyCell = row.CreateCell(4);
                moneyCell.SetCellValue((double)order.TotalAmount);
                moneyCell.CellStyle = moneyStyle;

                row.CreateCell(5).SetCellValue(order.Status);

                // 应用单元格样式
                for (int i = 0; i < headers.Length; i++)
                {
                    row.GetCell(i).CellStyle = cellStyle;
                }
            }

            // 自动调整列宽
            for (int i = 0; i < headers.Length; i++)
            {
                sheet.AutoSizeColumn(i);
                sheet.SetColumnWidth(i, Math.Min(sheet.GetColumnWidth(i) + 500, 8000));
            }

            // 冻结标题行
            sheet.CreateFreezePane(0, 1, 0, 1);

            // 写入内存流
            using (var ms = new MemoryStream())
            {
                workbook.Write(ms, true);
                return ms.ToArray();
            }
        }

        private string GenerateOrderNumber()
        {
            return $"ORD-{DateTime.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString().Substring(0, 4).ToUpper()}";
        }

        public async Task<PagedResult<Order>> QueryOrdersAsync(OrderQueryParameters parameters)
        {
            // 订单编号必填验证
            if (string.IsNullOrWhiteSpace(parameters.OrderNumber))
            {
                throw new ArgumentException("订单编号是必填查询条件", nameof(parameters.OrderNumber));
            }

            // 构建动态查询条件
            Expression<Func<Order, bool>> filter = o =>
                o.OrderNumber.Contains(parameters.OrderNumber);

            // 添加客户名称条件（如果提供）
            if (!string.IsNullOrWhiteSpace(parameters.CustomerName))
            {
                filter = filter.And(o =>
                    EF.Functions.Like(o.CustomerName, $"%{parameters.CustomerName}%"));
            }

            // 添加订单状态条件（如果提供）
            if (!string.IsNullOrWhiteSpace(parameters.Status))
            {
                filter = filter.And(o => o.Status == parameters.Status);
            }

            // 添加金额范围条件
            if (parameters.MinAmount.HasValue)
            {
                filter = filter.And(o => o.TotalAmount >= parameters.MinAmount.Value);
            }

            if (parameters.MaxAmount.HasValue)
            {
                filter = filter.And(o => o.TotalAmount <= parameters.MaxAmount.Value);
            }

            // 添加日期范围条件
            if (parameters.StartDate.HasValue)
            {
                filter = filter.And(o => o.OrderDate >= parameters.StartDate.Value);
            }

            if (parameters.EndDate.HasValue)
            {
                // 结束日期包含当天
                var endDate = parameters.EndDate.Value.AddDays(1).AddTicks(-1);
                filter = filter.And(o => o.OrderDate <= endDate);
            }

            return await _orderRepository.GetPagedAsync(
                parameters.Page,
                parameters.PageSize,
                filter);
        }

        public async Task<Order> UpdateOrderAsync(UpdateOrderDto dto)
        {
            // 验证必须提供ID或订单编号
            if (!dto.Id.HasValue && string.IsNullOrWhiteSpace(dto.OrderNumber))
            {
                throw new ArgumentException("必须提供订单ID或订单编号");
            }

            // 查找订单
            Order? order;
            if (dto.Id.HasValue)
            {
                order = await _orderRepository.GetByIdAsync(dto.Id.Value);
            }
            else
            {
                order = await _orderRepository.FindOneAsync(o => o.OrderNumber == dto.OrderNumber);
            }

            if (order == null)
            {
                throw new KeyNotFoundException("订单不存在");
            }

            // 部分更新字段
            if (!string.IsNullOrWhiteSpace(dto.CustomerName))
            {
                order.CustomerName = dto.CustomerName;
            }

            if (!string.IsNullOrWhiteSpace(dto.Status))
            {
                order.Status = dto.Status;
            }

            if (dto.TotalAmount.HasValue)
            {
                order.TotalAmount = dto.TotalAmount.Value;
            }

            try
            {
                _orderRepository.Update(order);
                await _orderRepository.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                // 重新加载实体以获取最新版本
                await _orderRepository.ReloadAsync(order);
                throw new DbUpdateConcurrencyException("更新订单时发生并发冲突", ex);
            }

            return order;
        }

        public async Task<bool> SimpleUpdateOrderAsync(SimpleUpdateOrderDto dto)
        {
            // 验证必须提供ID或订单编号
            if (!dto.Id.HasValue && string.IsNullOrWhiteSpace(dto.OrderNumber))
            {
                return false;
            }

            // 查找订单
            Order? order;
            if (dto.Id.HasValue)
            {
                order = await _orderRepository.GetByIdAsync(dto.Id.Value);
            }
            else
            {
                order = await _orderRepository.FindOneAsync(o => o.OrderNumber == dto.OrderNumber);
            }

            if (order == null)
            {
                return false;
            }

            // 记录是否有实际更新
            bool hasUpdate = false;

            // 部分更新字段
            if (!string.IsNullOrWhiteSpace(dto.CustomerName))
            {
                order.CustomerName = dto.CustomerName;
                hasUpdate = true;
            }

            if (!string.IsNullOrWhiteSpace(dto.Status))
            {
                order.Status = dto.Status;
                hasUpdate = true;
            }

            if (dto.TotalAmount.HasValue)
            {
                order.TotalAmount = dto.TotalAmount.Value;
                hasUpdate = true;
            }

            // 如果没有实际更新，直接返回true
            if (!hasUpdate)
            {
                return true;
            }

            try
            {
                _orderRepository.Update(order);
                await _orderRepository.SaveChangesAsync();
                return true;
            }
            catch
            {
                // 记录日志或处理异常
                return false;
            }
        }
        public async Task<bool> SoftDeleteOrderAsync(int id)
        {
            var order = await _orderRepository.GetByIdAsync(id);
            if (order == null)
            {
                return false;
            }

            // 标记为已删除
            order.IsDeleted = true;
            order.DeletedAt = DateTime.UtcNow;

            try
            {
                _orderRepository.Update(order);
                await _orderRepository.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                
                return false;
            }
        }
    }
}